package com.whc.gulimall.product.web;

import cn.hutool.core.lang.UUID;
import com.whc.gulimall.product.entity.CategoryEntity;
import com.whc.gulimall.product.service.CategoryService;
import com.whc.gulimall.product.vo.Catalog2Vo;
import org.redisson.api.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author angaoen
 */
@Controller
public class IndexController {

    /**
     * 商品三级分类 Service
     */
    @Resource
    private CategoryService categoryService;

    /**
     * Redisson 主接口，用于通过同步/异步接口访问所有 redisson 对象。
     */
    @Resource
    private RedissonClient redisson;

    /**
     * RedisTemplate 的以字符串为中心的扩展。
     */
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取一级分类并跳转到商城首页
     *
     * @param model 模型
     * @return 返回值
     */
    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        // 获取一级分类
        List<CategoryEntity> categoryEntityList = categoryService.listLevelOneCategory();
        model.addAttribute("categoryEntityList", categoryEntityList);
        return "index";
    }

    /**
     * 获取三级分类
     *
     * @return 三级分类
     */
    @GetMapping("/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        return categoryService.getCatalogJson();
    }

    @GetMapping("/hello")
    @ResponseBody
    public String hello() throws InterruptedException {
        RLock lock = redisson.getLock("anyLock");
        // 尝试加锁，最多等待100秒，上锁以后10秒自动解锁
        boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
        if (res) {
            System.out.println("获取锁--" + Thread.currentThread().getId());
            try {
                System.out.println("业务--" + Thread.currentThread().getId());
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                System.out.println("解锁--" + Thread.currentThread().getId());
                lock.unlock();
            }
        }
        return "hello";
    }

    @GetMapping("/read")
    @ResponseBody
    public String readValue() {
        RReadWriteLock rwlock = redisson.getReadWriteLock("anyRWLock");
        // 最常见的使用方法
        RLock rLock = rwlock.readLock();
        // 上锁
        rLock.lock();
        System.out.println("读锁" + Thread.currentThread().getId());

        String uuid = "";
        try {
            uuid = stringRedisTemplate.opsForValue().get("key");
            // 业务
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("解锁" + Thread.currentThread().getId());
            // 解锁
            rLock.unlock();
        }
        return uuid;
    }

    @GetMapping("/write")
    @ResponseBody
    public String writeValue() {
        RReadWriteLock rwlock = redisson.getReadWriteLock("anyRWLock");
        // 最常见的使用方法
        RLock rLock = rwlock.writeLock();
        // 上锁
        rLock.lock();
        System.out.println("写锁" + Thread.currentThread().getId());

        String uuid = "";
        try {
            uuid = UUID.fastUUID().toString();
            stringRedisTemplate.opsForValue().set("key", uuid);
            // 业务
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("解锁" + Thread.currentThread().getId());
            // 解锁
            rLock.unlock();
        }
        return uuid;
    }

    @GetMapping("/park")
    @ResponseBody
    public String park() {
        // 按名称返回信号量实例
        RSemaphore semaphore = redisson.getSemaphore("semaphore");
        // 尝试获取当前可用的许可证。
        // 如果获得了许可，则为true ，否则为false
        boolean flag = semaphore.tryAcquire();
        if (flag) {
            // 业务
        } else {
            // 业务
        }
        return "park--" + flag;
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() {
        // 按名称返回信号量实例
        RSemaphore semaphore = redisson.getSemaphore("semaphore");
        // 发放许可证。增加可用许可证的数量。
        semaphore.release();
        return "go";
    }

    @GetMapping("/lockSchool")
    @ResponseBody
    public String lockSchool() throws InterruptedException {
        // 按名称返回 countDownLatch 实例。
        RCountDownLatch latch = redisson.getCountDownLatch("anyCountDownLatch");
        // 仅当先前的计数已达到零或根本未设置时才设置新的计数值。
        latch.trySetCount(5);
        // 等到计数器达到零。
        latch.await();
        return "放学啦";
    }

    @GetMapping("/afterSchool")
    @ResponseBody
    public String afterSchool() {
        // 按名称返回 countDownLatch 实例。
        RCountDownLatch latch = redisson.getCountDownLatch("anyCountDownLatch");
        // 减少锁存器的计数器。当计数达到零时通知所有等待线程。
        latch.countDown();
        return "走了一个班";
    }
}
